package com.onion.mvc.resolver.builder;

import com.alibaba.fastjson.JSON;
import com.onion.mvc.enums.ParamPolicy;
import com.onion.mvc.utils.WebRequestUtils;
import com.onion.utils.surface.request.Request;
import com.onion.utils.surface.request.RequestHelper;
import com.onion.utils.utils.ClazzUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.http.HttpServletRequest;

public class BodyPriorParamBuilder implements RequestParamBuilder {

    @Override
    public ParamPolicy mode() {
        return ParamPolicy.BODY_PRIOR;
    }

    @Override
    public Request build(NativeWebRequest webRequest, MethodParameter parameter) {
        HttpServletRequest httpRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        String body = null;
        if("post".equals(httpRequest.getMethod().toLowerCase())){
            body = WebRequestUtils.getBodyData(httpRequest);
        }
        Request requestData = (Request)JSON.parseObject(body, parameter.getParameterType());
        if(requestData == null){
            requestData = (Request) ClazzUtils.newInstance(parameter.getParameterType());
            requestData.initRequest();
        }
        if(RequestHelper.isBasicType(parameter.getParameterType())){
            return this.fillBasicRequest(requestData, webRequest);
        }else{
            return this.fillComplexRequest(requestData, webRequest);
        }
    }

    /**
     * 补充、填充数据
     * @param request
     * @param webRequest
     * @return
     */
    private Request fillBasicRequest(Request request, NativeWebRequest webRequest){
        return request;
    }

    /**
     * 补充、填充数据
     * @param request
     * @param webRequest
     * @return
     */
    private Request fillComplexRequest(Request request, NativeWebRequest webRequest){
        return request;
    }

}